package com.jdone.compus.service;

import com.jdone.compus.model.BlowDeviceRepair;
import com.jdone.compus.model.BlowDeviceRepairImage;
import com.jdone.compus.repository.BlowDeviceRepairImageRepository;
import com.jdone.compus.repository.BlowDeviceRepairRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import java.net.MalformedURLException;

import javax.persistence.EntityNotFoundException;
import java.io.IOException;
import java.nio.file.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;



@Service
public class RepairImageService {


    @Value("${upload.image.base-dir}")
    private String baseDir;

    @Autowired
    private  BlowDeviceRepairRepository repairRepo;

    @Autowired
    private  BlowDeviceRepairImageRepository imageRepo;

    /**
     * 通用图片上传，不关联任何业务记录
     */
    public List<BlowDeviceRepairImage> storeImages(MultipartFile[] files) throws IOException {
        // 直接用 baseDir，不再按天建子目录
        Path dirPath = Paths.get(baseDir);
        if (!Files.exists(dirPath)) {
            Files.createDirectories(dirPath);
        }

        List<BlowDeviceRepairImage> saved = new ArrayList<>();
        for (MultipartFile file : files) {
            String original = file.getOriginalFilename();
            String ext = (original != null && original.contains("."))
                    ? original.substring(original.lastIndexOf('.')) : "";
            String fileName = UUID.randomUUID() + ext;
            Path target = dirPath.resolve(fileName);
            file.transferTo(target.toFile());

            BlowDeviceRepairImage img = new BlowDeviceRepairImage();
            img.setOriginalFilename(original);
            // relativePath 直接就是文件名
            img.setRelativePath(fileName);
            img.setUploadedAt(LocalDateTime.now());

            saved.add(imageRepo.save(img));
        }
        return saved;
    }


    /**
     * 加载图片资源并包装为 ResourceHolder
     */
    public ResourceHolder loadImage(String relativePath) {
        try {
            // 1. 去掉前端可能传来的 "/images/" 前缀，以及开头的 "/"
            String path = relativePath;
            if (path.startsWith("/")) {
                path = path.substring(1);
            }
            if (path.startsWith("images/")) {
                path = path.substring("images/".length());
            }

            // 2. 构造绝对路径
            Path file = Paths.get(baseDir).resolve(path).normalize();
            Resource resource = new UrlResource(file.toUri());
            if (!resource.exists() || !resource.isReadable()) {
                throw new EntityNotFoundException("文件不存在或不可读: " + path);
            }

            // 3. 自动探测 MIME 类型
            String contentType = Files.probeContentType(file);
            if (contentType == null) {
                contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
            }

            return new ResourceHolder(resource, contentType);

        } catch (MalformedURLException e) {
            throw new RuntimeException("文件 URL 错误: " + relativePath, e);
        } catch (EntityNotFoundException ex) {
            // 让控制器捕获并返回 404
            throw ex;
        } catch (Exception e) {
            throw new RuntimeException("加载文件失败: " + relativePath, e);
        }
    }

    /** 用于封装 Resource + MIME 类型 */
    public static class ResourceHolder {
        private final Resource resource;
        private final String contentType;

        public ResourceHolder(Resource resource, String contentType) {
            this.resource = resource;
            this.contentType = contentType;
        }
        public Resource getResource() {
            return resource;
        }
        public String getContentType() {
            return contentType;
        }
    }
}
